//
//  BabyDataAnalysis.m
//  airuiteHealth
//
//  Created by wusiping on 2021/3/20.
//  Copyright © 2021 wusiping. All rights reserved.
//

#import "BabyDataAnalysis.h"

@interface BabyDataAnalysis ()

@property (nonatomic,strong) NSMutableArray *bufferArray;
@property (nonatomic,assign) BOOL canAdd;
@end

@implementation BabyDataAnalysis

+ (NSMutableArray *)convertDataToHexStr:(NSData *)data {
    if (!data || [data length] == 0) {
        return nil;
    }
    // NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    
    /**
     将切割好的十六进制数塞入一个可变数组
     */
    NSMutableArray *dataArr = [NSMutableArray new];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        
        for (NSInteger i = 0; i < byteRange.length; i++) {
            
            /**
             将byte数组切割成一个个字符串
             */
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            // NSLog(@"%@",hexStr);
            /**
             因十六进制数据为 0X XXXX 以两字节为一位数,所以需要在切割出来的数据进行补零操作
             */
            
            if ([hexStr length] == 2) {
                // [string appendString:hexStr];
                [dataArr addObject:hexStr];
            } else {
                //[string appendFormat:@"0%@", hexStr];
                
                [dataArr addObject:[NSString stringWithFormat:@"0%@",hexStr]];
            }
        }
    }];
    // NSLog(@"-------->%@",dataArr);
    
    
    return dataArr;
}

/**
 十六进制转换为二进制
   
 @param hex 十六进制数
 @return 二进制数
 */
+ (NSString *)getBinaryByHex:(NSString *)hex {
    
    NSMutableDictionary *hexDic = [[NSMutableDictionary alloc] initWithCapacity:16];
    [hexDic setObject:@"0000" forKey:@"0"];
    [hexDic setObject:@"0001" forKey:@"1"];
    [hexDic setObject:@"0010" forKey:@"2"];
    [hexDic setObject:@"0011" forKey:@"3"];
    [hexDic setObject:@"0100" forKey:@"4"];
    [hexDic setObject:@"0101" forKey:@"5"];
    [hexDic setObject:@"0110" forKey:@"6"];
    [hexDic setObject:@"0111" forKey:@"7"];
    [hexDic setObject:@"1000" forKey:@"8"];
    [hexDic setObject:@"1001" forKey:@"9"];
    [hexDic setObject:@"1010" forKey:@"A"];
    [hexDic setObject:@"1011" forKey:@"B"];
    [hexDic setObject:@"1100" forKey:@"C"];
    [hexDic setObject:@"1101" forKey:@"D"];
    [hexDic setObject:@"1110" forKey:@"E"];
    [hexDic setObject:@"1111" forKey:@"F"];
    
    NSString *binary = @"";
    for (int i=0; i<[hex length]; i++) {
        
        NSString *key = [hex substringWithRange:NSMakeRange(i, 1)];
        NSString *value = [hexDic objectForKey:key.uppercaseString];
        if (value) {
            
            binary = [binary stringByAppendingString:value];
        }
    }
    return binary;
}

- (NSMutableArray *)bufferArray
{
    if (!_bufferArray) {
        _bufferArray = [NSMutableArray array];
    }
    return _bufferArray;
}

- (BOOL)canAdd
{
    if (!_canAdd) {
        _canAdd = NO;
    }
    return _canAdd;
}

- (void)anylisisDataWithData:(NSData *)data :(cmd55Block)cmd55block :(cmd56Block)cmd56block
{
    
//    NSMutableArray *dataArr = [BabyDataAnalysis convertDataToHexStr:data];
    NSMutableArray *tempArray = [BabyDataAnalysis convertDataToHexStr:data];
    
    for (int i = 0; i < tempArray.count; i ++) {
        NSString *value = tempArray[i];
        if ([value isEqual:@"fe"] && self.bufferArray.count == 0) {
            self.canAdd = YES;
            [self.bufferArray addObject:value];
        }else if ([value isEqual:@"fe"] && self.bufferArray.count) {
            NSArray *dataArr = [NSArray arrayWithArray:self.bufferArray];
           
            [self.bufferArray removeAllObjects];
            [self.bufferArray addObject:value];
            if (dataArr.count < 3) {
                continue;
            }
            NSString *cmd = dataArr[2];
            if ([cmd isEqualToString:@"55"]) {
                if (dataArr.count < 8) {
                    continue;
                }
                //脉率
                NSString *BpmStr = [NSString stringWithFormat:@"%@%@",dataArr[3],dataArr[4]];
                long BpmI = strtoul(BpmStr.UTF8String, 0, 16);
                //                                 NSLog(@"脉率，%lu",BpmI);

                //血氧
                NSString *SPO2Str = [NSString stringWithFormat:@"%@",dataArr[5]];
                long SPO2I = strtoul(SPO2Str.UTF8String, 0, 16);
                //                                 NSLog(@"血氧，%lu",SPO2I);

                //灌注指数
                NSString *PIStr = [NSString stringWithFormat:@"%@%@",dataArr[6],dataArr[7]];
                float PIf = strtoul(PIStr.UTF8String, 0, 16)/1000.0f;
                //                                 NSLog(@"灌注指数，%f",PIf);
                if (cmd55block) {
                    cmd55block(BpmI,SPO2I,PIf);
                }

            }else if ([cmd isEqualToString:@"56"]){
              
                if (dataArr.count < 6) {
                    continue;
                }
                //脉搏波数据
                NSString *wareformStr = [NSString stringWithFormat:@"%@",dataArr[3]];
        //        NSLog(@"当前脉搏波数据%@",wareformStr);
                float wareform = fabsf(100 - strtoul(wareformStr.UTF8String, 0, 16)/1.0f);
        //        NSLog(@"脉搏波数据，%f",wareform);
        //        NSLog(@"当前脉搏波数据====%f",wareform);

                //棒图
                NSString *stickGraphStr = [NSString stringWithFormat:@"%@",dataArr[5]];
                long stickGraph = strtoul(stickGraphStr.UTF8String, 0, 16);
//                                                 NSLog(@"棒图，%lu",stickGraph);

                //状态
                NSString *stateStr = [NSString stringWithFormat:@"%@",dataArr[4]];
                NSString *stateBinaryStr = [BabyDataAnalysis getBinaryByHex:stateStr];
                //                                 NSLog(@"16进制状态%@",stateStr);
                //
                //                                 NSLog(@"二进制状态%@",stateBinaryStr);

                NSString *bit0 = [stateBinaryStr substringWithRange:NSMakeRange(7, 1)];
                NSString *bit1 = [stateBinaryStr substringWithRange:NSMakeRange(6, 1)];
                NSString *bit2 = [stateBinaryStr substringWithRange:NSMakeRange(5, 1)];
                NSString *bit3 = [stateBinaryStr substringWithRange:NSMakeRange(4, 1)];
                NSString *result = @"";
                NSInteger state = 0;
                if ([bit0 integerValue] == 1) {
                    result = @"无脉搏音";
                    state = 1;
                }
                if ([bit1 integerValue] == 1) {//导联脱落
                    result = FYLocalizedString(@"oxygen_tips2", @"");
                    state = 2;
                }
                if ([bit2 integerValue] == 1) {//运动干扰
                    result = FYLocalizedString(@"oxygen_tips1", @"");
                    state = 3;
                }
                if ([bit3 integerValue] == 1) {
                    result = @"低灌注";
                    state = 4;
                }
                
                if (cmd56block) {
                    cmd56block(wareform,result,state,stickGraph);
                }
            }else {
                NSLog(@"cmd ===%@ ==== %@",cmd,dataArr);
            }
        }else if (self.canAdd){
            [self.bufferArray addObject:value];
        }
        
    }

//    NSLog(@"dataarray ==== %@",dataArr);
   
  
}

@end
